<template>
  <div class="login-container">
    <div class="login-header">
      <div class="logo">
        <img alt="LOGO" :src="logoSrc" width="100%" height="100%" @error="logoError" />
      </div>
    </div>
    <div class="login-body">
      <div class="login-animate"></div>
      <div class="login-form-wrap">
        <h3 class="login-title">欢迎登录</h3>
        <p class="sys-title">{{platName}}</p>
        <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          auto-complete="on"
          label-position="left"
          @submit.native.prevent
        >
          <el-form-item prop="username">
            <span class="svg-container">
              <i icon-class="user" />
            </span>
            <el-input
              ref="username"
              v-model="loginForm.username"
              name="username"
              type="text"
              auto-complete="on"
              placeholder="用户名/手机号"
              @keyup.enter.native="handleLogin()"
              clearable
            />
          </el-form-item>
          <el-form-item prop="password">
            <span class="svg-container">
              <i icon-class="password" />
            </span>
            <el-input
              ref="password"
              type="password"
              v-model="loginForm.password"
              name="password"
              auto-complete="on"
              placeholder="密码"
              @keyup.enter.native="handleLogin()"
              show-password
            />
          </el-form-item>
          <p class="forget" @click="dialogForgetPsw=true">
            忘记密码?
            <a>立即找回</a>
          </p>
          <el-form-item>
            <el-button :loading="loading" type="primary" style="width:100%;" @click.native.prevent="handleLogin()">登录</el-button>
          </el-form-item>
          <div class="tips">
            <!-- <span style="margin-right:20px;">username: admin</span>
            <span> password: admin</span>-->
          </div>
        </el-form>
      </div>
      <div class="foot">Copyright {{new Date().getFullYear()}} All Rights Reserved</div>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      title="忘记密码"
      width="550px"
      top="25vh"
      :visible.sync="dialogForgetPsw"
      @close="closeForgetPsw"
    >
      <el-row class="user-info-form" type="flex" justify="center">
        <el-col>
          <el-form
            label-width="110px"
            :model="forgetPswForm"
            :rules="forgetPswRules"
            ref="forgetPswForm"
            @submit.native.prevent
          >
            <el-form-item label="手机号：" prop="tel">
              <el-input name="tel" type="text" v-model="forgetPswForm.tel" auto-complete="off" placeholder="请输入手机号"></el-input>
            </el-form-item>
            <el-form-item label="验证码：" prop="code">
              <el-input
                name="code"
                type="text"
                v-model="forgetPswForm.code"
                auto-complete="off"
                placeholder="请输入验证码"
                :style="{width: '50%'}"
              ></el-input>
              <el-button
                :type="verifyCodeButtonType"
                :disabled="disabled"
                @click="getVerifyCode"
                :style="{marginLeft: marginLeft}"
              >{{time}}</el-button>
            </el-form-item>
            <el-form-item label="新密码：" prop="newPassword">
              <el-input
                name="newPassword"
                type="password"
                v-model="forgetPswForm.newPassword"
                auto-complete="off"
                placeholder="请输入新密码"
                show-password
              ></el-input>
            </el-form-item>
            <el-form-item label="重复密码：" prop="againPsw">
              <el-input
                name="againPsw"
                type="password"
                v-model="forgetPswForm.againPsw"
                auto-complete="off"
                placeholder="请输入确认密码"
                show-password
              ></el-input>
            </el-form-item>
            <p class="color-2">密码规则：·6~16位英文、“-”、“_”或数字·不允许有空格·不允许有中文</p>
            <el-form-item label-width="0" class="verifyidentity-button">
              <el-button @click="closeForgetPsw">取消</el-button>
              <el-button type="primary" @click="updatePsw('forgetPswForm')">提交</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { isvalidUsername, isvalidPassword, validphone } from '@/utils/validate'
import { findOrgByOrgCode } from '@/api/api'
import { mapActions, mapState } from 'vuex'
import { sendVerifyCode, forgetPwd, getNewAppV } from '@/api/api'
var platOnlyKey = ''
export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!isvalidUsername(value) || value.length < 2 || value.length > 16) {
        callback(new Error('请输入正确的用户名'))
      } else {
        callback()
      }
    }
    const validatePass = (rule, value, callback) => {
      if (value.length < 5) {
        callback(new Error('密码不能小于5位'))
      } else {
        callback()
      }
    }
    const mobile = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号码'))
      } else if (!validphone(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }
    const newPassword = (rule, value, callback) => {
      if (!isvalidPassword(value) || value.length < 6 || value.length > 16) {
        callback(new Error('请输入正确的密码格式'))
      } else {
        callback()
      }
    }
    const againPsw = (rule, value, callback) => {
      if (this.forgetPswForm.newPassword !== this.forgetPswForm.againPsw) {
        this.forgetPswForm.againPsw = ''
        callback(new Error('两次输入密码不一致，请重新输入！'))
      } else {
        callback()
      }
    }
    const verifycode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入验证码'))
      } else {
        callback()
      }
    }
    return {
      /*  TODO通过是否记住密码给输入框赋值  */
      loginForm: {
        username: '',
        password: '',
      },
      loginRules: {
        username: [
          { required: true, trigger: 'blur', validator: validateUsername },
        ],
        password: [
          { required: true, trigger: 'blur', validator: validatePass },
        ],
      },
      loading: false,
      pwdType: 'password',
      redirect: undefined,
      dialogForgetPsw: false,
      forgetPswForm: {
        tel: '',
        code: '',
        newPassword: '',
        againPsw: '',
      },
      forgetPswRules: {
        tel: [{ required: true, trigger: 'blur', validator: mobile }],
        code: [{ required: true, trigger: 'blur', validator: verifycode }],
        newPassword: [
          { required: true, trigger: 'blur', validator: newPassword },
        ],
        againPsw: [{ required: true, trigger: 'blur', validator: againPsw }],
      },
      disabled: false,
      marginLeft: '58px',
      verifyCodeButtonType: 'primary',
      time: '发送验证码',
      platformCode: PLATCOEDEFAULT,
      logoSrc: '',
      platName: '智慧消防综合监管平台',
    }
  },
  computed: {
    ...mapState(['userinfo', 'isLogin']),
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true,
    },
  },
  created() {
    this.platformCode = this.GLOBAL.getPlatFormCodeByUrl()
    if (CONFIGBOX[CONFIGKEY].platName) {
      this.platName = CONFIGBOX[CONFIGKEY].platName
    }
    this.getLogoSrc()
    //获取分平台key
    findOrgByOrgCode({ orgCode: this.platformCode }).then((re) => {
      localStorage.setItem('ilink_platformCode_platId', re.data || '')
      platOnlyKey =
        localStorage.getItem('ilink_platformCode_platId') ||
        (this.userinfo && this.userinfo.org ? this.userinfo.org.id : 0)
      this.$nextTick(() => {
        this.getClientFEVersion()
      })
    })
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
    if(this.$route.query.account){
      this.loginForm.username=this.$route.query.account
      this.loginForm.password='123456'
      this.handleLogin(true)
    }
  },
  methods: {
    ...mapActions(['requestLogin']),
    getClientFEVersion() {
      getNewAppV({
        organizationId: platOnlyKey,
        type: 7,
      }).then((res) => {
        if (res.data) {
          let v = parseInt(localStorage.getItem('ILINK_CLIETN_FE_VERSION') || 0)
          if (res.data.softNumber > v) {
            localStorage.setItem('ILINK_CLIETN_FE_VERSION', res.data.softNumber)
            // 触发客户端清除缓存，此代码不能删除！
            console.log('清除客户端缓存')
          }
        }
      })
    },
    getLogoSrc() {
      this.logoSrc =
        REMOTESTATICPATH + this.platformCode + '/pc/login/logo/logo.png'
    },
    logoError(e) {
      this.logoSrc =
        REMOTESTATICPATH + PLATCOEDEFAULT + '/pc/login/logo/logo.png'
    },
    handleLogin(isAuto) {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true
          //NProgress.start();
          var loginParams = {
            accountName: this.loginForm.username,
            password: isAuto?this.$route.query.password:this.$md5(this.loginForm.password),
            isEncrypt: true,
            loginId:
              this.platformCode == PLATCOEDEFAULT ? '' : this.platformCode,
          }
          this.requestLogin(loginParams).then((res) => {
            this.loading = false
            if (this.isLogin) {
              //若是使用用户信息，则本地保存用户信息，根据需求自行使用本地保存方式
              localStorage.setItem('userInfo', JSON.stringify(this.userinfo))
              this.$router.push({ path: '/home' })
            } else {
              localStorage.setItem('userInfo', '')
              if (this.userinfo.status === 200) {
                this.$message({
                  message: '该用户无权限登录',
                  type: 'error',
                })
              } else {
                this.$message({
                  message: this.userinfo.info,
                  type: 'error',
                })
              }
            }
          })
        } else {
          // console.log('error submit!!');
          return false
        }
      })
    },
    updatePsw(formName) {
      let that = this
      this.$refs.forgetPswForm.validate((valid) => {
        if (valid) {
          let parames = {
            tel: that.forgetPswForm.tel,
            code: that.forgetPswForm.code,
            isEncrypt: true,
            newPassword: that.$md5(that.forgetPswForm.newPassword),
          }
          forgetPwd(parames).then((res) => {
            if (status === 200) {
              that.$message({
                message: '密码修改成功，请重新登录！',
                type: 'success',
              })
            } else {
              that.$message({
                message: res.info,
                type: 'warning',
              })
            }
          })
        }
      })
    },
    closeForgetPsw() {
      ;(this.dialogForgetPsw = false),
        // 重置基本信息
        this.$refs['forgetPswForm'].resetFields()
    },
    getVerifyCode() {
      let that = this
      let mobile = that.forgetPswForm.tel
      if (mobile === '' || !/^1\d{10}$/.test(mobile)) {
        that.$refs.forgetPswForm.validateField('tel')
      } else {
        let pram = {
          tel: mobile,
        }
        sendVerifyCode(pram).then((res) => {
          if (res.status === 200) {
            that.$message({
              message: '验证码发送成功！',
              type: 'success',
            })
            // 倒计时开始
            that.disabled = true
            that.marginLeft = '29px'
            that.verifyCodeButtonType = 'info'
            that.startCodeTime(60)
          } else {
            that.$message({
              message: res.info,
              type: 'warning',
            })
          }
        })
      }
    },
    startCodeTime(value) {
      let that = this
      if (value === 0) {
        that.time = '发送验证码'
        that.marginLeft = '58px'
        that.verifyCodeButtonType = 'primary'
        that.disabled = false
      } else {
        value -= 1
        that.time = value + '秒后重新获取'
        setTimeout(function () {
          that.startCodeTime(value)
        }, 1000)
      }
    },
  },
}
</script>

<style>
.login-form .el-input input,
.login-form .el-button {
  border-radius: 40px;
}
.login-form .el-button {
  height: 40px;
  letter-spacing: 5px;
  font-size: 16px;
  font-weight: bold;
}
</style>
<style rel="stylesheet/scss" lang="scss">
.login-container {
  position: relative;
  width: 100%;
  height: 100%;
  min-width: 1200px;
  overflow-y: auto;
}
.login-animate {
  position: absolute;
  z-index: 1;
  width: 450px;
  height: 450px;
  left: 50%;
  margin-left: -550px;
  background: url(../../assets/images/login/animate-login.png) no-repeat left
    top / cover content-box;
  overflow: hidden;
  animation: loginAnim 3s ease-in infinite;
  -moz-animation: loginAnim 3s ease-in infinite;
  -webkit-animation: loginAnim 3s ease-in infinite;
  -o-animation: loginAnim 3s ease-in infinite;
}
@keyframes loginAnim {
  0% {
    top: 222px;
  }
  50% {
    top: 205px;
  }
  100% {
    top: 222px;
  }
}
@-moz-keyframes loginAnim {
  0% {
    top: 222px;
  }
  50% {
    top: 205px;
  }
  100% {
    top: 222px;
  }
}
@-webkit-keyframes loginAnim {
  0% {
    top: 222px;
  }
  50% {
    top: 205px;
  }
  100% {
    top: 222px;
  }
}
@-o-keyframes loginAnim {
  0% {
    top: 222px;
  }
  50% {
    top: 205px;
  }
  100% {
    top: 222px;
  }
}
.login-header {
  display: flex;
  align-items: center;
  width: 100%;
  height: 12%;
  background-color: #fff;
  .logo {
    margin-left: 50px;
  }
}

.login-body {
  position: relative;
  width: 100%;
  height: 88%;
  min-height: 820px;
  background: url(../../assets/images/login/login-bg.jpg) center 0 no-repeat;
  .login-form-wrap {
    position: absolute;
    top: 250px;
    right: 10%;
    padding: 20px;
    width: 360px;
    height: 370px;
    background: #fff;
    border: 1px solid #bdbdbd;
    border-radius: 3px;
    box-sizing: border-box;
    .login-title {
      cursor: default;
      letter-spacing: 1px;
      margin: 20px 0 0 0;
      line-height: 30px;
      font-size: 30px;
      color: #205ea7;
    }
    .sys-title {
      letter-spacing: 1px;
      cursor: default;
      margin: 15px 0 0 0;
      line-height: 22px;
      font-size: 22px;
      color: #666;
    }
    .login-form {
      margin-top: 30px;
      .forget {
        margin-bottom: 15px;
        padding-right: 10px;
        text-align: right;
        color: #666;
      }
    }
  }
  .foot {
    position: absolute;
    top: 100%;
    margin-top: -50px;
    width: 100%;
    height: 50px;
    line-height: 50px;
    color: #fff;
    font-size: 14px;
    text-align: center;
  }
}
</style>
